package com.finance.system.file.service;

import com.finance.system.file.enums.ParentFolder;
import com.finance.system.file.entity.FileSystemEntity;
import com.finance.system.support.utils.Assert;
import com.finance.system.file.entity.PhysicalFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.*;
import java.time.LocalDateTime;

@Service
public class PhysicalFileService {


    private final Logger logger = LoggerFactory.getLogger(PhysicalFileService.class);


    @Autowired
    private IFileSystemService fileSystemService;

    @Value("${file.base.dir}")
    private String fileBaseDir;

    public PhysicalFile getFile(Long fileId) {
        FileSystemEntity fileSystemEntity = fileSystemService.getById(fileId);
        return PhysicalFile.from(fileSystemEntity);
    }

    public PhysicalFile fromMultipartFile(MultipartFile file, ParentFolder parentFolder){
        //1.检查文件，没有则报异常
        try {
            Assert.notNull(file.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        FileSystemEntity systemEntity = createFile(file,parentFolder);
        fileSystemService.save(systemEntity);
        //2.生成即将保存的文件路径
        Path path  = createPath(parentFolder,systemEntity);
        //3.递归检查文件夹是否存在，否则创建
        checkAndCompletePath(path);
        //4.写io，将文件保存
        saveFile(file,path);
        //5.构造对象返回
        return new PhysicalFile(systemEntity,null);

    }

    private void saveFile(MultipartFile file, Path path) {
        try {
            Files.copy(file.getInputStream(),path);
        } catch (IOException e) {
            logger.error("file copy error :"+ e.getMessage());
        }
    }

    private void checkAndCompletePath(Path path) {
        if(Files.exists(path)){
            return;
        }
        Path parent1 = path.getParent();
        if(!Files.exists(parent1)){
            try {
                Files.createDirectories(parent1);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        Path path = Paths.get("/Users/whdong/resource/file/test/aaa.txt");
        if(Files.exists(path)){
            return;
        }
        Path parent1 = path.getParent();
        if(!Files.exists(parent1)){
            try {
                Files.createDirectories(parent1);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private  Path createPath(ParentFolder parentFolder, FileSystemEntity fileEntity) {

        Path path = Paths.get(fileBaseDir).resolve(parentFolder.name())
                .resolve(fileEntity.getYearFolder().toString())
                .resolve(fileEntity.getMonthFolder().toString())
                .resolve(fileEntity.getId().toString() + "." + fileEntity.getFileExtension());
        return path;

    }

    private FileSystemEntity createFile(MultipartFile file, ParentFolder parentFolder){
        LocalDateTime now = LocalDateTime.now();
        int year = now.getYear();
        int month = now.getMonthValue();
        String fileName = file.getOriginalFilename();
        FileSystemEntity fileSystemEntity = new FileSystemEntity().setFileName(fileName)
                .setFileSize(file.getSize())
                .setParentFolder(parentFolder.name())
                .setYearFolder(year)
                .setMonthFolder(month)
                .setFileSize(file.getSize())
                .setFileExtension(fileName.substring(fileName.lastIndexOf(".") + 1));
        return fileSystemEntity;

    }
}
